//
//  DeskTop.swift
//  DeskTop
//
//  Created by zhouzuosong on 2020/10/19.
//  Copyright © 2020 Kael. All rights reserved.
//

import WidgetKit
import SwiftUI
import Intents

// MARK: ------ TimeLine config ------
struct Provider: IntentTimelineProvider {
    
    // placeholder Timeline config
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), configuration: ConfigurationIntent())
    }

    // 截屏方法时间驱动配置
    func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), configuration: configuration)
        completion(entry)
    }

    // 时间线配置
    func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [SimpleEntry] = []

        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
            let entry = SimpleEntry(date: entryDate, configuration: configuration)
            entries.append(entry)
        }
        // 设置刷新策略 .atEnd
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }
}

struct SimpleEntry: TimelineEntry {
    let date: Date
    let configuration: ConfigurationIntent
//    let configuration: WidgetConfiguratIntent

}

struct MenuJson: Codable {
    let id: String
    let name: String
    let image: String
    
    static func createMenuList() -> [MenuJson] {
        var list = [MenuJson]()
        list.append(.init(id: "1", name: "西红柿炒鸡蛋", image: ""))
        list.append(.init(id: "2", name: "水煮肉片", image: ""))
        list.append(.init(id: "3", name: "白菜粉条", image: ""))
        list.append(.init(id: "4", name: "鱼香肉丝", image: ""))
        return list
    }
}
// MARK: ------ small ------
struct SmallWidget : View {
    @State var entry: Provider.Entry
    
    private let groupID = "group.widget.swiftui.demo"

    private let sharedDefaults = UserDefaults(suiteName: "group.widget.swiftui.demo")
    
    private let imagePath = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.widget.swiftui.demo")
    private let imageData = UIImage(data: Data())
    
    func getImageFromGroup(imagePath:URL?) -> UIImage? {
        let imagePath = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.widget.swiftui.demo")
//        let imageData = try! Data(contentsOf: imagePath)
        
        return UIImage(contentsOfFile: imagePath?.absoluteString ?? "")
//        return UIImage(data: imageData)
    }
    
    var body: some View {
        VStack(spacing: 6) {
            Text(entry.date, style: .time)
                .background(Color.pink)
            
            Text(sharedDefaults?.string(forKey: "groupName") ?? "NO Data")
                .background(Color.green)
                .frame(maxWidth:.infinity)
                .foregroundColor(.white)
            
            Text("Placeholder - \((sharedDefaults?.integer(forKey: "userdata"))!)")
            
            Image("\(String(describing: imagePath?.absoluteString))")
                .resizable()
                .frame(minWidth: 40)

        }
//        .background(Color.orange)
        .widgetURL(URL(string: "com.lexue.SwiftUIDemo"))
    }
}
// MARK: ------ medium ------
struct MediumWidget : View {
    @State var entry: Provider.Entry
    @State var liveStatus: Int = 2
    @State var dateString:String = "今"
    @State var liveTimeString:String = "10:00-12:00"
    @State var subjectString:String = "语文"
    @State var goodsName:String = "乐学语文大讲堂乐学语文大讲堂乐学语文大讲堂乐学语文大讲堂乐…"
    @State var teacherName:String = "乐学曹老师"
    
    var body: some View {
        
        ZStack {
            Color(.sRGB, red: 0, green: 0, blue: 0, opacity: 0.3)

            Color(.sRGB, red: 0, green: 0, blue: 0, opacity: 0.2)
                .blur(radius: 100)
            
            VStack(alignment:.leading) {
                HStack(alignment: .center) {
                    Text(dateString)
                        .padding(2)
                        .background(Color(.sRGB, red: 50/255, green: 190/255, blue: 100/255, opacity: 1))
                        .cornerRadius(4.0)
                        .foregroundColor(.white)
                        .font(.system(size: 11))
                    
                    Text(liveTimeString)
                        .font(.system(size: 15))
                        .foregroundColor(Color(.sRGB, red: 19/255, green: 19/255, blue: 19/255, opacity: 1))

                    
                }
    //            .background(Color.gray)
                .padding(3)
                
                HStack(alignment: .top) {
                    Text(subjectString)
                        .padding(2)
                        .background(Color(.sRGB, red: 50/255, green: 190/255, blue: 100/255, opacity: 1))
                        .cornerRadius(4.0)
                        .foregroundColor(.white)
                        .font(.system(size: 11))
                        .padding(2)
                    
                    Text(goodsName)
                        .font(.system(size: 15))
                        .foregroundColor(Color(.sRGB, red: 19/255, green: 19/255, blue: 19/255, opacity: 1))
                        .lineLimit(2)

                    
                    Text(liveStatusMessage())
                        .padding(2)
                        .background(liveStatusColor())
                        .cornerRadius(4.0)
                        .foregroundColor(.white)
                        .font(.system(size: 11))
                        .padding(EdgeInsets(top: 2, leading: 10, bottom: 2, trailing: 10))

                    
                }
                .padding(3)
                
                Text("讲师: \(teacherName)")
                    .font(.system(size: 11))
                    .foregroundColor(Color(.sRGB, red: 100/255, green: 100/255, blue: 100/255, opacity: 1))
                    .padding(2)
                
            }
            .frame(minWidth: 200)
            .padding()
            .cornerRadius(8)
        }
        

    }
    
    func liveStatusColor() -> Color {
        var liveColor = Color(.sRGB, red: 181/255, green: 184/255, blue: 189/255, opacity: 1)
        if liveStatus == 0 {
            liveColor = Color(.sRGB, red: 255/255, green: 52/255, blue: 51/255, opacity: 1)
        }else if liveStatus == 1 {
            liveColor = Color(.sRGB, red: 50/255, green: 190/255, blue: 100/255, opacity: 1)
        }else{
            liveColor = Color(.sRGB, red: 181/255, green: 184/255, blue: 189/255, opacity: 1)
        }
        return liveColor
    }
    
    func liveStatusMessage() -> String {
        var statusMessage = ""
        if liveStatus == 0 {
            statusMessage = "未开始"
        }else if liveStatus == 1 {
            statusMessage = "进行中"
        }else{
            statusMessage = "已结束"
        }
        return statusMessage
    }
    
}
// MARK: ------ Large ------
struct LargeWidget : View {
    @State var entry: Provider.Entry
    let largeImage: UIImage? = nil
    let placeholderOne = UIImage(named: "screen")

    var body: some View {
        LXLiveRootView()
    }
}

struct DeskTopEntryView : View {
    var entry: Provider.Entry
    
    @Environment(\.widgetFamily) var family: WidgetFamily

    @ViewBuilder
    var body: some View {
        switch family {
        case .systemSmall:
            SmallWidget(entry: entry)
        case .systemMedium:
            MediumWidget(entry: entry)
        case .systemLarge:
            LargeWidget(entry: entry)
        default:
            Text(entry.date, style: .time)
        }
        
    }
}

@main

struct LXLiveWidget : WidgetBundle {
    
    var body: some Widget {
       
        DeskTop1()
        DeskTop2()

   }
}

struct DeskTop1: Widget {
    let kind: String = "com.lexue.SwiftUIDemo.DeskTop"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
            DeskTopEntryView(entry: entry)
        }
        .configurationDisplayName("直播小组件")
        .description("This is an example widget for U.")
    }
}

struct DeskTop2: Widget {
    let kind: String = "com.lexue.SwiftUIDemo.DeskTop"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
            DeskTopEntryView(entry: entry)
        }
        .configurationDisplayName("222直播小组件----222")
        .description("This is an example widget for U.")
    }
}

struct DeskTop_Previews: PreviewProvider {
    static var previews: some View {
        DeskTopEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent()))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
        
        DeskTopEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent()))
            .previewContext(WidgetPreviewContext(family: .systemMedium))
        
        DeskTopEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent()))
            .previewContext(WidgetPreviewContext(family: .systemLarge))

    }
}
